(function(){
	window.Distance = (function(){
		
		var Distance = {};
		Distance.EARTH_R = 6378.137;
		Distance.degreesToRadians = function(deg){
			return deg * (Math.PI / 180);
		};
		Distance.radiansToDegrees = function(rad){
			return rad / (Math.PI / 180);
		};
		
		Distance.calcDistance = function (lat1,lng1,lat2,lng2){
			lat1 = parseFloat(lat1);
			lng1 = parseFloat(lng1);
			lat2 = parseFloat(lat2);
			lng2 = parseFloat(lng2);
			var f = this.degreesToRadians((lat1 + lat2) /2);
			var g = this.degreesToRadians((lat1 - lat2)/2);
			var l = this.degreesToRadians((lng1 - lng2)/2);
			var sg = Math.sin(g);
			var sl = Math.sin(l);
			var sf = Math.sin(f);
			
			var s,c,w,r,d,h1,h2;
			var a = this.EARTH_R;
			var fl = 1/298.257;
			sg = sg*sg;
			sl = sl*sl;
			sf = sf*sf;

			s = sg*(1-sl) + (1-sf)*sl;
			c = (1-sg)*(1-sl) + sf*sl;

			w = Math.atan(Math.sqrt(s/c));
			r = Math.sqrt(s*c)/w;
			d = 2*w*a;
			h1 = (3*r -1)/2/c;
			h2 = (3*r +1)/2/s;
			
			var value =  d*(1 + fl*(h1*sf*(1-sg) - h2*(1-sf)*sg));
			//四舍五入，保留3位精度
			return Distance.round(value,3);
		};
		Distance.round = function (v, p) {
			var t = 1;
			for (; p > 0; t *= 10, p--);
			for (; p < 0; t /= 10, p++);
			return Math.round(v * t) / t;
		} 
		Distance.distance = function (latLng1,latLng2){
			return this.calcDistance(latLng1.lat(),latLng1.lng(),latLng2.lat(),latLng2.lng());
		};
		return Distance;
	})();
})();